package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    /**
     * 新建功能 新增套餐
     *
     * @param setmeal
     * @param checkgroupIds
     */
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增的数据
        setmealDao.add(setmeal);
        //表之间的关系
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //将图片保存到redis中
        savePic2Redis(setmeal.getImg());
        //在增删改方法后 都需要生成静态页面
        generateMobileStaticHtml();
    }


    //生成静态页面
    public void generateMobileStaticHtml() {
        //包括套餐列表 套餐详情
        //先准备数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //生成套餐列表静态页面 调方法
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面 有 多个
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表静态页面  方法
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map map = new HashMap();
        map.put("setmealList", setmealList);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);

    }

    //生成套餐详情静态页面   方法
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map map = new HashMap();
            map.put("setmeal", setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }


    //写一个通用的生成静态页面的方法  三个参数 1.模板文件 2.写入的文件  3.参数
    public void generateHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据  位置
            OutputStream fos = new FileOutputStream(outPutPath + "/" + htmlPageName);

            out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //查询所有
    public List<Setmeal> findAll() {

        return setmealDao.findAll();
    }

    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    private void savePic2Redis(String pic) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
    }

    /**
     * 定义方法  复用
     *
     * @param id
     * @param checkgroupIds
     */
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<String, Integer>();
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }
}
